import json
import logging
import os


class JSONFormatter(logging.Formatter):

    def __init__(self, fmt, dfmt, style):
        super().__init__(fmt, dfmt, style)
        try:
            from celery._state import get_current_task
            self.get_current_task = get_current_task
        except ImportError:
            self.get_current_task = lambda: None

        """
        :param tags: a list of tags to add to every messages
        :hostname: force a specific hostname
        :fqdn: a boolean to use the FQDN instead of the machine's hostname
        :message_type: the message type for Logstash formatters
        :indent: indent level of the JSON output
        """
        # self.message_type = message_type
        # self.tags = tags if tags is not None else []
        # self.extra_tags = []
        # self.indent = indent
        #
        # if hostname:
        #     self.host = hostname
        # elif fqdn:
        #     self.host = socket.getfqdn()
        # else:
        #     self.host = socket.gethostname()

    def format(self, record, serialize=True):

        task = self.get_current_task()
        if task and task.request:
            record.__dict__.update(task_id=task.request.id,
                                   task_name=task.name)

        else:
            record.__dict__.setdefault('task_name', '')
            record.__dict__.setdefault('task_id', '')
        if record.__dict__.get("data"):
            record.__dict__.pop("data")
        return super().format(record)
        # new_message = record.getMessage()
        # # Create message dict
        # message = {
        #     'timestamp': self.formatTime(record),
        #     'app': os.environ.get('APP_NAME'),
        #     'host': self.host,
        #     'environment': os.environ.get('FLASK_ENV'),
        #     'logger': record.name,
        #     'level': record.levelname,
        #     'message': new_message,
        #     'path': record.pathname,
        #     'tags': self.tags[:]
        # }

    #     # Add extra fields
    #     message.update(self.get_extra_fields(record))
    #
    #     # Add extra tags
    #     if self.extra_tags:
    #         message['tags'].extend(self.extra_tags)
    #
    #     # If exception, add debug info
    #     if record.exc_info or record.exc_text:
    #         message.update(self.get_debug_fields(record))
    #
    #     if serialize:
    #         return self.serialize(message, indent=self.indent)
    #     return message
    #
    # def get_debug_fields(self, record):
    #     return {}
    #
    # def get_extra_fields(self, record):
    #     return {}
    #
    # def serialize(self, message, indent):
    #     return json.dumps(message)
